//引入ajax
import { login } from "./request.js"
// 获取元素
// var inpAll = document.querySelectorAll("input");
let name = document.querySelector("#name");
let phone = document.querySelector("#phone");
let idName = document.querySelector("#idName");
let myBtn = document.querySelector(".myBtn")
let startBtn = document.querySelector(".startBtn")
// 按钮点击事件
myBtn.addEventListener("click", check);
startBtn.addEventListener("click", check);
name.addEventListener("blur", nameFn);
phone.addEventListener("blur", phoneFn);
idName.addEventListener("blur", cardFn);
// 正则验证
let nameReg = /^[\u4E00-\u9FA5]{2,10}(·[\u4E00-\u9FA5]{2,10}){0,2}$/;
let phoneReg = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
let cardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
// 名字
function nameFn() {
    if (!nameReg.test(name.value)) {
        name.nextElementSibling.innerHTML = "请输入正确中文名";
        name.nextElementSibling.style.color = "red";
    } else {
        name.nextElementSibling.innerHTML = "成功";
        name.nextElementSibling.style.color = "green";
    }
}
// 号码
function phoneFn() {
    if (!phoneReg.test(phone.value)) {
        phone.nextElementSibling.innerHTML = "请输入正确号码";
        phone.nextElementSibling.style.color = "red";
    } else {
        phone.nextElementSibling.innerHTML = "成功";
        phone.nextElementSibling.style.color = "green";
    }
}
// 身份证
function cardFn() {
    if (!cardReg.test(idName.value)) {
        idName.nextElementSibling.innerHTML = "请输入正确身份证号";
        idName.nextElementSibling.style.color = "red";
    } else {
        idName.nextElementSibling.innerHTML = "成功";
        idName.nextElementSibling.style.color = "green";
    }
}
async function check(e) {
    nameFn()
    phoneFn()
    cardFn()
    // ajax参数
    let data = {
        "name": name.value,
        "phone": phone.value,
        "card": idName.value
    }
    let res = await login(data)
    // 全部验证成功
    if (nameReg.test(name.value) && phoneReg.test(phone.value) && cardReg.test(idName.value)) {
        // console.log(res);
        // 保存到缓存里面
        sessionStorage.setItem("name", name.value);
        sessionStorage.setItem("phone", phone.value);
        sessionStorage.setItem("card", idName.value);
        sessionStorage.setItem("token", res.result.token);
        // 页面跳转
        if (e.target.className == "myBtn") {
            location.href = "./mybook.html"
        } else {
            location.href = "./book.html"
        }
    }
}